package master;

import java.util.*;
import javax.swing.*;

import master.event.*;

/**
 * WorkspaceContext provides a framework for the project's workspaces to run
 * in a multi-tabbed environment
 * @author s0932248
 *
 */

public class WorkspaceContext implements WorkspaceEventInitiator{
	//all workspaces present in the application at any given time
	private static List<Workspace> workspaces = new ArrayList<Workspace>();
	private static String defaultWorkspaceName= "untitled";
	private static int defaultWorkspaceDim = 3;
	
	public void createWorkspace(QuantumNetwork k, String prefferedName){
		String name = prefferedName;
		int dup = 0;
		while(!checkNameAvailability(name)){
			dup ++;
			name = prefferedName + "("+dup+")";
		}
		Workspace w;
		if(k == null){
			w = new Workspace(name, new QuantumNetwork(new QuantumRegister(defaultWorkspaceDim)));
		}else
			w = new Workspace(name,k);
		
		workspaces.add(w);
		workspaceCreatedEvent(w);
	}
	
	public void createWorkspace(QuantumNetwork k){
		createWorkspace(k,defaultWorkspaceName);
	}
	
	public void destroyWorkspace(Workspace k){
		int deleteWorkspace = 1;
		deleteWorkspace =
			JOptionPane.showConfirmDialog(new JFrame(), "Are you sure you want to close " + k.getName() + "?");
		if(deleteWorkspace == 0){
			int count = -1;
			for(int i  = 0 ; i < workspaces.size() ;i++)
				if(workspaces.get(i).equals(k)) count = i;
			
			
			if(count != -1) workspaces.remove(count);
			
		}
		workspaceDestroyedEvent(k);
	}
	
	private boolean checkNameAvailability(String name){
		for(Workspace wspce : workspaces)
			if(  wspce.getName().equals(name)  ) return false;
		return true;
	}
	public Workspace [] getActiveWorkspaces(){
		Workspace [] arr = new Workspace[workspaces.size()];
		for(int i = 0 ; i < arr.length ;i++)
			arr[i] = workspaces.get(i);
		return arr;
	}


	List<WorkspaceEventListener> listeners = new ArrayList<WorkspaceEventListener>();
	
	public void addWorkspaceListener(WorkspaceEventListener l) {
		listeners.add(l);
	}
	
	public void workspaceCreatedEvent(Workspace createdWorkspace){
		WorkspaceEvent e = new WorkspaceEvent(this,0,"Workspace Created",createdWorkspace);
		for(WorkspaceEventListener l : listeners){
			l.workspaceEvent(e);
		}
	}
	public void workspaceDestroyedEvent(Workspace destroyedWorkspace){
		WorkspaceEvent e = new WorkspaceEvent(this,0,"Workspace Destroyed",destroyedWorkspace);
		for(WorkspaceEventListener l : listeners){
			l.workspaceEvent(e);
		}
	}
	
	@Override
	public void initiateWorkspaceEvent() {}
}
